package qldc.pm.tiensu.service.persistence;

import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.UnmodifiableList;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import qldc.pm.tiensu.NoSuchTangThuException;
import qldc.pm.tiensu.model.TangThu;
import qldc.pm.tiensu.model.impl.TangThuImpl;
import qldc.pm.tiensu.model.impl.TangThuModelImpl;
import qldc.pm.tiensu.service.persistence.TangThuPersistence;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the tang thu service.
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Brian Wing Shun Chan
 * @see TangThuPersistence
 * @see TangThuUtil
 * @generated
 */
public class TangThuPersistenceImpl extends BasePersistenceImpl<TangThu>
    implements TangThuPersistence {
    /*
     * NOTE FOR DEVELOPERS:
     *
     * Never modify or reference this class directly. Always use {@link TangThuUtil} to access the tang thu persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
     */
    public static final String FINDER_CLASS_NAME_ENTITY = TangThuImpl.class.getName();
    public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
        ".List1";
    public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
        ".List2";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuModelImpl.FINDER_CACHE_ENABLED, TangThuImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuModelImpl.FINDER_CACHE_ENABLED, TangThuImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
    private static final String _SQL_SELECT_TANGTHU = "SELECT tangThu FROM TangThu tangThu";
    private static final String _SQL_COUNT_TANGTHU = "SELECT COUNT(tangThu) FROM TangThu tangThu";
    private static final String _ORDER_BY_ENTITY_ALIAS = "tangThu.";
    private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No TangThu exists with the primary key ";
    private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
                PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
    private static Log _log = LogFactoryUtil.getLog(TangThuPersistenceImpl.class);
    private static TangThu _nullTangThu = new TangThuImpl() {
            @Override
            public Object clone() {
                return this;
            }

            @Override
            public CacheModel<TangThu> toCacheModel() {
                return _nullTangThuCacheModel;
            }
        };

    private static CacheModel<TangThu> _nullTangThuCacheModel = new CacheModel<TangThu>() {
            @Override
            public TangThu toEntityModel() {
                return _nullTangThu;
            }
        };

    public TangThuPersistenceImpl() {
        setModelClass(TangThu.class);
    }

    /**
     * Caches the tang thu in the entity cache if it is enabled.
     *
     * @param tangThu the tang thu
     */
    @Override
    public void cacheResult(TangThu tangThu) {
        EntityCacheUtil.putResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuImpl.class, tangThu.getPrimaryKey(), tangThu);

        tangThu.resetOriginalValues();
    }

    /**
     * Caches the tang thus in the entity cache if it is enabled.
     *
     * @param tangThus the tang thus
     */
    @Override
    public void cacheResult(List<TangThu> tangThus) {
        for (TangThu tangThu : tangThus) {
            if (EntityCacheUtil.getResult(
                        TangThuModelImpl.ENTITY_CACHE_ENABLED,
                        TangThuImpl.class, tangThu.getPrimaryKey()) == null) {
                cacheResult(tangThu);
            } else {
                tangThu.resetOriginalValues();
            }
        }
    }

    /**
     * Clears the cache for all tang thus.
     *
     * <p>
     * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
     * </p>
     */
    @Override
    public void clearCache() {
        if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
            CacheRegistryUtil.clear(TangThuImpl.class.getName());
        }

        EntityCacheUtil.clearCache(TangThuImpl.class.getName());

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
    }

    /**
     * Clears the cache for the tang thu.
     *
     * <p>
     * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
     * </p>
     */
    @Override
    public void clearCache(TangThu tangThu) {
        EntityCacheUtil.removeResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuImpl.class, tangThu.getPrimaryKey());

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
    }

    @Override
    public void clearCache(List<TangThu> tangThus) {
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

        for (TangThu tangThu : tangThus) {
            EntityCacheUtil.removeResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
                TangThuImpl.class, tangThu.getPrimaryKey());
        }
    }

    /**
     * Creates a new tang thu with the primary key. Does not add the tang thu to the database.
     *
     * @param tangThuId the primary key for the new tang thu
     * @return the new tang thu
     */
    @Override
    public TangThu create(long tangThuId) {
        TangThu tangThu = new TangThuImpl();

        tangThu.setNew(true);
        tangThu.setPrimaryKey(tangThuId);

        return tangThu;
    }

    /**
     * Removes the tang thu with the primary key from the database. Also notifies the appropriate model listeners.
     *
     * @param tangThuId the primary key of the tang thu
     * @return the tang thu that was removed
     * @throws qldc.pm.tiensu.NoSuchTangThuException if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu remove(long tangThuId)
        throws NoSuchTangThuException, SystemException {
        return remove((Serializable) tangThuId);
    }

    /**
     * Removes the tang thu with the primary key from the database. Also notifies the appropriate model listeners.
     *
     * @param primaryKey the primary key of the tang thu
     * @return the tang thu that was removed
     * @throws qldc.pm.tiensu.NoSuchTangThuException if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu remove(Serializable primaryKey)
        throws NoSuchTangThuException, SystemException {
        Session session = null;

        try {
            session = openSession();

            TangThu tangThu = (TangThu) session.get(TangThuImpl.class,
                    primaryKey);

            if (tangThu == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
                }

                throw new NoSuchTangThuException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                    primaryKey);
            }

            return remove(tangThu);
        } catch (NoSuchTangThuException nsee) {
            throw nsee;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    @Override
    protected TangThu removeImpl(TangThu tangThu) throws SystemException {
        tangThu = toUnwrappedModel(tangThu);

        Session session = null;

        try {
            session = openSession();

            if (!session.contains(tangThu)) {
                tangThu = (TangThu) session.get(TangThuImpl.class,
                        tangThu.getPrimaryKeyObj());
            }

            if (tangThu != null) {
                session.delete(tangThu);
            }
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        if (tangThu != null) {
            clearCache(tangThu);
        }

        return tangThu;
    }

    @Override
    public TangThu updateImpl(qldc.pm.tiensu.model.TangThu tangThu)
        throws SystemException {
        tangThu = toUnwrappedModel(tangThu);

        boolean isNew = tangThu.isNew();

        Session session = null;

        try {
            session = openSession();

            if (tangThu.isNew()) {
                session.save(tangThu);

                tangThu.setNew(false);
            } else {
                session.merge(tangThu);
            }
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);

        if (isNew) {
            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
        }

        EntityCacheUtil.putResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
            TangThuImpl.class, tangThu.getPrimaryKey(), tangThu);

        return tangThu;
    }

    protected TangThu toUnwrappedModel(TangThu tangThu) {
        if (tangThu instanceof TangThuImpl) {
            return tangThu;
        }

        TangThuImpl tangThuImpl = new TangThuImpl();

        tangThuImpl.setNew(tangThu.isNew());
        tangThuImpl.setPrimaryKey(tangThu.getPrimaryKey());

        tangThuImpl.setTangThuId(tangThu.getTangThuId());
        tangThuImpl.setUserId(tangThu.getUserId());
        tangThuImpl.setUserName(tangThu.getUserName());
        tangThuImpl.setCreateDate(tangThu.getCreateDate());
        tangThuImpl.setModifiedDate(tangThu.getModifiedDate());
        tangThuImpl.setSoSoHoKhau(tangThu.getSoSoHoKhau());
        tangThuImpl.setDiaChiThuongTru(tangThu.getDiaChiThuongTru());
        tangThuImpl.setDiaChiThuongTruTinhId(tangThu.getDiaChiThuongTruTinhId());
        tangThuImpl.setDiaChiThuongTruQuanHuyenId(tangThu.getDiaChiThuongTruQuanHuyenId());
        tangThuImpl.setDiaChiThuongTruPhuongXaId(tangThu.getDiaChiThuongTruPhuongXaId());
        tangThuImpl.setDoiTuongTienSuId(tangThu.getDoiTuongTienSuId());
        tangThuImpl.setHoVaTenNguoiCoTienSu(tangThu.getHoVaTenNguoiCoTienSu());
        tangThuImpl.setNgayLuu(tangThu.getNgayLuu());
        tangThuImpl.setViTriLuu(tangThu.getViTriLuu());
        tangThuImpl.setLapMoi(tangThu.isLapMoi());
        tangThuImpl.setChuThich(tangThu.getChuThich());

        return tangThuImpl;
    }

    /**
     * Returns the tang thu with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
     *
     * @param primaryKey the primary key of the tang thu
     * @return the tang thu
     * @throws qldc.pm.tiensu.NoSuchTangThuException if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu findByPrimaryKey(Serializable primaryKey)
        throws NoSuchTangThuException, SystemException {
        TangThu tangThu = fetchByPrimaryKey(primaryKey);

        if (tangThu == null) {
            if (_log.isWarnEnabled()) {
                _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
            }

            throw new NoSuchTangThuException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                primaryKey);
        }

        return tangThu;
    }

    /**
     * Returns the tang thu with the primary key or throws a {@link qldc.pm.tiensu.NoSuchTangThuException} if it could not be found.
     *
     * @param tangThuId the primary key of the tang thu
     * @return the tang thu
     * @throws qldc.pm.tiensu.NoSuchTangThuException if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu findByPrimaryKey(long tangThuId)
        throws NoSuchTangThuException, SystemException {
        return findByPrimaryKey((Serializable) tangThuId);
    }

    /**
     * Returns the tang thu with the primary key or returns <code>null</code> if it could not be found.
     *
     * @param primaryKey the primary key of the tang thu
     * @return the tang thu, or <code>null</code> if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu fetchByPrimaryKey(Serializable primaryKey)
        throws SystemException {
        TangThu tangThu = (TangThu) EntityCacheUtil.getResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
                TangThuImpl.class, primaryKey);

        if (tangThu == _nullTangThu) {
            return null;
        }

        if (tangThu == null) {
            Session session = null;

            try {
                session = openSession();

                tangThu = (TangThu) session.get(TangThuImpl.class, primaryKey);

                if (tangThu != null) {
                    cacheResult(tangThu);
                } else {
                    EntityCacheUtil.putResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
                        TangThuImpl.class, primaryKey, _nullTangThu);
                }
            } catch (Exception e) {
                EntityCacheUtil.removeResult(TangThuModelImpl.ENTITY_CACHE_ENABLED,
                    TangThuImpl.class, primaryKey);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return tangThu;
    }

    /**
     * Returns the tang thu with the primary key or returns <code>null</code> if it could not be found.
     *
     * @param tangThuId the primary key of the tang thu
     * @return the tang thu, or <code>null</code> if a tang thu with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public TangThu fetchByPrimaryKey(long tangThuId) throws SystemException {
        return fetchByPrimaryKey((Serializable) tangThuId);
    }

    /**
     * Returns all the tang thus.
     *
     * @return the tang thus
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<TangThu> findAll() throws SystemException {
        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the tang thus.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link qldc.pm.tiensu.model.impl.TangThuModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param start the lower bound of the range of tang thus
     * @param end the upper bound of the range of tang thus (not inclusive)
     * @return the range of tang thus
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<TangThu> findAll(int start, int end) throws SystemException {
        return findAll(start, end, null);
    }

    /**
     * Returns an ordered range of all the tang thus.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link qldc.pm.tiensu.model.impl.TangThuModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param start the lower bound of the range of tang thus
     * @param end the upper bound of the range of tang thus (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of tang thus
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<TangThu> findAll(int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
            finderArgs = FINDER_ARGS_EMPTY;
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
            finderArgs = new Object[] { start, end, orderByComparator };
        }

        List<TangThu> list = (List<TangThu>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if (list == null) {
            StringBundler query = null;
            String sql = null;

            if (orderByComparator != null) {
                query = new StringBundler(2 +
                        (orderByComparator.getOrderByFields().length * 3));

                query.append(_SQL_SELECT_TANGTHU);

                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);

                sql = query.toString();
            } else {
                sql = _SQL_SELECT_TANGTHU;

                if (pagination) {
                    sql = sql.concat(TangThuModelImpl.ORDER_BY_JPQL);
                }
            }

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                if (!pagination) {
                    list = (List<TangThu>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<TangThu>(list);
                } else {
                    list = (List<TangThu>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Removes all the tang thus from the database.
     *
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeAll() throws SystemException {
        for (TangThu tangThu : findAll()) {
            remove(tangThu);
        }
    }

    /**
     * Returns the number of tang thus.
     *
     * @return the number of tang thus
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countAll() throws SystemException {
        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
                FINDER_ARGS_EMPTY, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(_SQL_COUNT_TANGTHU);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
                    FINDER_ARGS_EMPTY, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_ALL,
                    FINDER_ARGS_EMPTY);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Initializes the tang thu persistence.
     */
    public void afterPropertiesSet() {
        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
                    com.liferay.util.service.ServiceProps.get(
                        "value.object.listener.qldc.pm.tiensu.model.TangThu")));

        if (listenerClassNames.length > 0) {
            try {
                List<ModelListener<TangThu>> listenersList = new ArrayList<ModelListener<TangThu>>();

                for (String listenerClassName : listenerClassNames) {
                    listenersList.add((ModelListener<TangThu>) InstanceFactory.newInstance(
                            getClassLoader(), listenerClassName));
                }

                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
            } catch (Exception e) {
                _log.error(e);
            }
        }
    }

    public void destroy() {
        EntityCacheUtil.removeCache(TangThuImpl.class.getName());
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
    }
}
